package com.sk.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

public class EchoClient {
    private final int port;
    private final String host;
    public EchoClient(String host, int port){
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception{
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            //创建Bootstrap
            Bootstrap bootstrap = new Bootstrap();
                bootstrap.group(eventLoopGroup)//指定EventLoopGroup,处理客户端事件。需要适应nio的实现。
                        .channel(NioSocketChannel.class)//适用于nio的channel类型
                        .remoteAddress(new InetSocketAddress(this.host,this.port))//设置服务器的InetSocketAddress
                        .handler(new ChannelInitializer<SocketChannel>() {//创建channel时，向channelPipeline中添加一个EchoClineHandler实例
                            @Override public void initChannel(SocketChannel socketChannel) throws Exception {
                                socketChannel.pipeline().addLast(new EchoClientHandlerIn())
                                                        .addLast(new EchoClientHandlerOut());
                            }
                        });
            ChannelFuture future = bootstrap.connect().sync();//连接到远程节点并阻塞直到链接完成
            future.addListener(new ChannelFutureListener() {
                @Override public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    System.out.println("我在监听她们");
                }
            });
            future.channel().closeFuture().sync();//阻塞直到channel关闭。
        }finally {
            eventLoopGroup.shutdownGracefully().sync();//关闭线程池并释放所有资源
        }
    }

    public static void main(String[] args) throws Exception{
        new EchoClient("127.0.0.1",18080).start();
    }
}
